import { forwardRef, useEffect } from 'react';
import { Drawer, message } from 'antd';
import { getMessage } from '@inbiz/react';
import './style.less';

const ProcessDrawerDetail: React.ForwardRefRenderFunction<
  any,
  {
    url: string;
    version: string;
    doneHandler: Function;
    unmount: Function;
    drawerParams: any;
  }
> = (props, ref) => {
  const { url, drawerParams, version, doneHandler, unmount } = props;

  useEffect(() => {
    if (version == 'v5') {
      let timer = setInterval(() => {
        let iframeWindow = document.getElementById(url)?.contentWindow;
        if (iframeWindow?.eform?.formEngine?.isLoaded) {
          clearInterval(timer);
          let controlWrapper = iframeWindow?.document.getElementsByClassName(
            'edoc2WorkFlowButtonContainer',
          )[0];
          let controlId = controlWrapper?.getAttribute('controlid');
          iframeWindow
            ?.eform(controlId)
            ?.method('afterSubmit', function (param: { result: boolean }) {
              if (param.result === true) {
                unmount && unmount();
                message.success({ content: getMessage('processCenter.operateSuccess'), key: 'process-easy-view-drawer-approval-success' });
                doneHandler && doneHandler();
              }
            });
        }
      }, 100);
    } else {
      let timer = setInterval(() => {
        let iframeWindow = document.getElementById(url)?.contentWindow;
        if (iframeWindow?.inbiz) {
          clearInterval(timer);
          iframeWindow?.inbiz?.on('saveData', function (res: any) {
            if (res) {
              let timer1 = setInterval(() => {
                let ifSuccess = localStorage.getItem('process-easy-view-approval-success');
                if (ifSuccess == 'true') {
                  clearInterval(timer1);
                  unmount && unmount();
                  message.success({ content: getMessage('processCenter.operateSuccess'), key: 'process-easy-view-drawer-approval-success' });
                  doneHandler && doneHandler();
                }
              }, 100);
            }
          });
        }
      }, 100);
    }
  }, [version, url]);

  return (
    <Drawer {...drawerParams}>
      <iframe
        id={url}
        style={{
          height: '100%',
          width: '100%',
          border: 'none',
          overflow: 'auto',
          borderRadius: 8,
        }}
        src={url}
      />
    </Drawer>
  );
};

export default forwardRef(ProcessDrawerDetail);
